package com.fc.mall.service.impl;

import com.fc.mall.dto.*;
import com.fc.mall.mapper.OmsOrderItemMapper;
import com.fc.mall.model.*;
import com.fc.mall.service.SmsNoticeService;
import com.fc.mall.util.DateTimeHelper;
import com.fc.mall.util.Utils;
import com.github.pagehelper.PageHelper;
import com.fc.mall.dao.OmsOrderDao;
import com.fc.mall.dao.OmsOrderOperateHistoryDao;
import com.fc.mall.mapper.OmsOrderMapper;
import com.fc.mall.mapper.OmsOrderOperateHistoryMapper;
import com.fc.mall.service.OmsOrderService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单管理Service实现类
 * Created by dobuy on 2018/10/11.
 */
@Service
public class OmsOrderServiceImpl implements OmsOrderService {
    @Autowired
    private OmsOrderMapper orderMapper;
    @Autowired
    private OmsOrderDao orderDao;
    @Autowired
    private OmsOrderOperateHistoryDao orderOperateHistoryDao;
    @Autowired
    private OmsOrderOperateHistoryMapper orderOperateHistoryMapper;

    @Autowired
    private OmsOrderItemMapper orderItemMapper;

    @Autowired
    private SmsNoticeService noticeService;

    @Override
    public List<OmsOrder> list(OmsOrderQueryParam queryParam, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        if (!StringUtils.isEmpty(queryParam.getMemberUsername())){
            queryParam.setMemberUsername(Utils.urlEncoderTransfer(queryParam.getMemberUsername()));
        }
        List<OmsOrder> omsOrderList =  orderDao.getList(queryParam);
        if (null != omsOrderList && !omsOrderList.isEmpty())
        {
            omsOrderList.forEach(order ->{
                OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
                OmsOrderItemExample.Criteria orderItemExampleCriteria = orderItemExample.createCriteria();
                orderItemExampleCriteria.andOrderIdEqualTo(order.getId());
                List<OmsOrderItem> omsOrderItems = orderItemMapper.selectByExample(orderItemExample);
                order.setOrderItemList(omsOrderItems);

                order.setMemberUsername(Utils.urlDecoderTransfer(order.getMemberUsername()));

                /**
                 * 数据库node存储为：红旗颜色-订单备注
                 * 红旗颜色：1:红  2：灰  3：绿  4：蓝  5：紫
                 */
                if (!StringUtils.isEmpty(order.getNote())){
                    String[] node = order.getNote().split("-");
                    if (node.length>1){
                        order.setColor(Integer.parseInt(node[0]));
                        order.setNote(node[1]);
                    }else {
                        //没有设置旗子颜色的订单默认为红色
                        order.setColor(1);
                        order.setNote(node[0]);
                    }
                }
            });
        }
        return omsOrderList;




    }

    @Override
    public List<OmsOrder> getFansOrderList(Long memberId, Integer pageNum, Integer pageSize) {
        OmsOrderQueryParam omsOrderQueryParam = new OmsOrderQueryParam();
        omsOrderQueryParam.setMemberId(memberId);
        List<OmsOrder> omsOrderList =  list(omsOrderQueryParam, pageSize, pageNum);
        return omsOrderList;
    }

    @Override
    public int delivery(List<OmsOrderDeliveryParam> deliveryParamList) {
        //批量发货
        int count = orderDao.delivery(deliveryParamList);
        //添加操作记录
        List<OmsOrderOperateHistory> operateHistoryList = deliveryParamList.stream()
                .map(omsOrderDeliveryParam -> {
                    OmsOrderOperateHistory history = new OmsOrderOperateHistory();
                    history.setOrderId(omsOrderDeliveryParam.getOrderId());
                    history.setCreateTime(new Date());
                    history.setOperateMan("后台管理员");
                    history.setOrderStatus(2);
                    history.setNote("完成发货");
                    return history;
                }).collect(Collectors.toList());
        orderOperateHistoryDao.insertList(operateHistoryList);
        sendNoticeToOrderOwner(deliveryParamList);
        return count;
    }

    @Override
    public int close(List<Long> ids, String note) {
        OmsOrder record = new OmsOrder();
        record.setStatus(4);
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andDeleteStatusEqualTo(0).andIdIn(ids);
        int count = orderMapper.updateByExampleSelective(record, example);
        List<OmsOrderOperateHistory> historyList = ids.stream().map(orderId -> {
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(orderId);
            history.setCreateTime(new Date());
            history.setOperateMan("后台管理员");
            history.setOrderStatus(4);
            history.setNote("订单关闭:"+note);
            return history;
        }).collect(Collectors.toList());
        orderOperateHistoryDao.insertList(historyList);
        return count;
    }

    @Override
    public int delete(List<Long> ids) {
        OmsOrder record = new OmsOrder();
        record.setDeleteStatus(1);
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andDeleteStatusEqualTo(0).andIdIn(ids);
        return orderMapper.updateByExampleSelective(record, example);
    }

    @Override
    public OmsOrderDetail detail(Long id) {
        OmsOrderDetail orderDetail = orderDao.getDetail(id);
        /**
         * 数据库node存储为：红旗颜色-订单备注
         * 红旗颜色：1:红  2：灰  3：绿  4：蓝  5：紫
         */
        if (!StringUtils.isEmpty(orderDetail.getNote())){
            String[] node = orderDetail.getNote().split("-");
            if (node.length>1){
                orderDetail.setColor(Integer.parseInt(node[0]));
                orderDetail.setNote(node[1]);
            }else {
                //没有设置旗子颜色的订单默认为红色
                orderDetail.setColor(1);
                orderDetail.setNote(node[0]);
            }
        }
        return orderDetail;
    }

    @Override
    public int updateReceiverInfo(OmsReceiverInfoParam receiverInfoParam) {
        OmsOrder order = new OmsOrder();
        order.setId(receiverInfoParam.getOrderId());
        order.setReceiverName(receiverInfoParam.getReceiverName());
        order.setReceiverPhone(receiverInfoParam.getReceiverPhone());
        order.setReceiverPostCode(receiverInfoParam.getReceiverPostCode());
        order.setReceiverDetailAddress(receiverInfoParam.getReceiverDetailAddress());
        order.setReceiverProvince(receiverInfoParam.getReceiverProvince());
        order.setReceiverCity(receiverInfoParam.getReceiverCity());
        order.setReceiverRegion(receiverInfoParam.getReceiverRegion());
        order.setModifyTime(new Date());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(receiverInfoParam.getOrderId());
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(receiverInfoParam.getStatus());
        history.setNote("修改收货人信息");
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public int updateMoneyInfo(OmsMoneyInfoParam moneyInfoParam) {
        OmsOrder order = new OmsOrder();
        order.setId(moneyInfoParam.getOrderId());
        order.setFreightAmount(moneyInfoParam.getFreightAmount());
        order.setDiscountAmount(moneyInfoParam.getDiscountAmount());
        order.setModifyTime(new Date());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        //插入操作记录
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(moneyInfoParam.getOrderId());
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setOrderStatus(moneyInfoParam.getStatus());
        history.setNote("修改费用信息");
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public int updateNote(Long id, String note, Integer status) {
        OmsOrder order = new OmsOrder();
        order.setId(id);
        /**
         * status仅此处特殊处理表示订单备注红旗颜色:
         * 1:红  2：灰  3：绿  4：蓝  5：紫
         */
        order.setNote(status+"-"+note);
        order.setModifyTime(new Date());
        int count = orderMapper.updateByPrimaryKeySelective(order);
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(id);
        history.setCreateTime(new Date());
        history.setOperateMan("后台管理员");
        history.setNote("修改备注信息："+note);
        orderOperateHistoryMapper.insert(history);
        return count;
    }

    @Override
    public List<OmsOrderItemDetail> getAllOrderItemDetails(OmsOrderQueryParam queryParam) {
        if (!StringUtils.isEmpty(queryParam.getMemberUsername())){
            queryParam.setMemberUsername(Utils.urlEncoderTransfer(queryParam.getMemberUsername()));
        }
        List<OmsOrderItemDetail> orderItemDetailList = orderDao.getOrderItemDetails(queryParam);
        for (OmsOrderItemDetail orderItem : orderItemDetailList) {
            /**
             * 数据库node存储为：红旗颜色-订单备注
             * 红旗颜色：1:红  2：灰  3：绿  4：蓝  5：紫
             */
            if (!StringUtils.isEmpty(orderItem.getNote())){
                String[] node = orderItem.getNote().split("-");
                if (node.length>1){
                    orderItem.setColor(Integer.parseInt(node[0]));
                    orderItem.setNote(node[1]);
                }else {
                    //没有设置旗子颜色的订单默认为红色
                    orderItem.setColor(1);
                    orderItem.setNote(node[0]);
                }
            }
        }
        return orderItemDetailList;
    }

    @Override
    public List<OmsCentCommossion> queryCentCommossionByOrderId(Long orderId) {
        OmsOrder order = orderMapper.selectByPrimaryKey(orderId);
        List<OmsCentCommossion> centCommossionList = orderDao.queryCentCommossionByOrderId(order.getOrderSn());
        if(null != centCommossionList && !centCommossionList.isEmpty())
        {
            centCommossionList.forEach(commossion -> {
                commossion.setOrderSn(order.getOrderSn());
                commossion.setOwner(order.getMemberId().equals(commossion.getMemberId()));
               try {
                   String nickname = commossion.getNickname();
                   if(!StringUtils.isEmpty(nickname))
                   {
                       commossion.setNickname(URLDecoder.decode(nickname, "utf-8"));
                   }
               }catch (Exception e){
                   e.printStackTrace();
               }
            });
        }
        return centCommossionList;
    }


    private void sendNoticeToOrderOwner(List<OmsOrderDeliveryParam> orderDeliveryParamList)
    {
        for(OmsOrderDeliveryParam orderDeliveryParam : orderDeliveryParamList)
        {
            JSONObject json = new JSONObject();
            OmsOrder order = orderMapper.selectByPrimaryKey(orderDeliveryParam.getOrderId());

            json.put("memberId", order.getMemberId());
            json.put("companyName", orderDeliveryParam.getDeliveryCompany());
            json.put("trackingNumber", orderDeliveryParam.getDeliverySn());
            json.put("orderSn", order.getOrderSn());
            json.put("receiver", order.getReceiverName());
            StringBuilder detailAddress = new StringBuilder(order.getReceiverProvince())
                    .append(order.getReceiverCity())
                    .append(order.getReceiverRegion())
                    .append(order.getReceiverDetailAddress());
            json.put("receiveAddress", detailAddress.toString());
            json.put("deliveryDate", DateTimeHelper.getStringFromDate(new Date(), DateTimeHelper.PAYLOAD_DATEONLY));
            json.put("noticeType", 1);
            noticeService.sendNotice(json.toString());
        }
    }
}
